package com.example.myapplication.ui.notifications;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.myapplication.BleGATT.BleGattServer;
import com.example.myapplication.BleGATT.ClientUtils;
import com.example.myapplication.Entity.MessageEntity;
import com.example.myapplication.Entity.SendBoxAdapter;
import com.example.myapplication.R;
import com.example.myapplication.RunActivity;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("MissingPermission")
public class TalkingFragment extends Fragment {
    private SendBoxAdapter SEadapter;
    private List<MessageEntity>messageList = new ArrayList<>();
    private RunActivity mActivity;

    private ClientUtils clientUtils;

    private TalkingViewModel viewModel; // 用于保存消息数据

    private BleGattServer mBleGattServer; // 保存BleGattServer实例的成员变量


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof RunActivity) {
            mActivity = (RunActivity) context;
        }
        Intent gattServiceIntent = new Intent(getActivity(), BleGattServer.class);
        getActivity().bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel = mActivity.getViewModel();
    }
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_talking, container, false);
        Button sendButton = (Button) view.findViewById(R.id.send_button);
        TextView  SendDate = (TextView) view.findViewById(R.id.send_data);
        ListView listView = view.findViewById(R.id.messge_box);
        mActivity= (RunActivity) getActivity();
        if (mActivity != null) {
            clientUtils = mActivity.getClientUtils();
        }

        SEadapter = new SendBoxAdapter(getActivity(), messageList);
        listView.setAdapter(SEadapter);
//数据监视
        viewModel.getMessageList().observe(getActivity(), messages -> {
            Log.d("TAG","消息更新");
            SEadapter.setMessages(messages);
        });

        sendButton.setOnClickListener(v -> {
            String msg = SendDate.getText().toString();
            //去空行
            msg = msg.replaceAll("^[\\s\n]+|[\\s\n]+$", "");

            if (msg.length() == 0) {
                Toast.makeText(mActivity, "字符为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!clientUtils.isBluetoothConnected()) {
                Toast.makeText(mActivity, "蓝牙未连接无法发送", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                if (mActivity.getisServer()) {
                    //读取
                    mBleGattServer.setCharacteristicValue(msg);
                } else {
                    //写入
                    clientUtils.sendData(msg);
                }
                MessageEntity message = new MessageEntity();
                message.setState(false);
                message.setMesssage(msg);
                addSendMessage(message);
                SendDate.setText("");
            }catch (Exception e){
                Toast.makeText(mActivity, "消息发送失败，稍后重试", Toast.LENGTH_SHORT).show();
            }


        });


        return view;
    }
    /**
     * 绑定GATT server
     */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BleGattServer.LocalBinder binder = (BleGattServer.LocalBinder) service;
            mBleGattServer = binder.getService();
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBleGattServer = null;
        }
    };
    /**
     * @param message 视图更新
     */
    public void addSendMessage(MessageEntity message) {
        viewModel.addMessage(message);
        SEadapter.notifyDataSetChanged();
    }

    public SendBoxAdapter getAdapter() {
        return SEadapter;
    }
}
